package com.css.gitstats.service.gitlab;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.gitstats.config.GitlabProperties;
import com.css.gitstats.domain.AuthorList;
import com.css.gitstats.service.GitstatsStatistics;
import com.google.common.collect.Lists;

import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GitlabGitstatsStatisticsService implements GitstatsStatistics {

	@Autowired
	private GitlabProperties gitlabProperties;
	
	@Override
	public List<AuthorList> getAuthorLists(String projectName) {
		List<AuthorList> authorLists = Lists.newArrayList();
		
		String gitStatsUrl = String.format(gitlabProperties.getGitstatsUrl(), projectName);
		log.info("拼接后的地址: {}", gitStatsUrl);
        HttpRequest request = HttpRequest.get(gitStatsUrl);
        String html = request.execute().body();

        Document doc = Jsoup.parse(html);
        Element table = doc.getElementById("authors");
        
        Elements rows = table.select("tr");
        for (Element row : rows) {
        	if(row.siblingIndex() == 0) {
        		continue;
        	}
            Elements columns = row.select("th, td");
            AuthorList commitStats = new AuthorList();
            commitStats.setAuthor(columns.get(0).text());
            commitStats.setCommitsPercent(columns.get(1).text());
            commitStats.setPlusLines(columns.get(2).text());
            commitStats.setMinusLines(columns.get(3).text());
            commitStats.setFirstCommit(columns.get(4).text());
            commitStats.setLastCommit(columns.get(5).text());
            commitStats.setAge(columns.get(6).text());
            commitStats.setActiveDays(columns.get(7).text());
            commitStats.setCommitsCount(columns.get(8).text());

            authorLists.add(commitStats);
        }
        return authorLists;
    }
}
